﻿using System;
using System.CodeDom.Compiler;
using System.Linq;

namespace SmartStringResources.CodeDom
{
	public static class CodeDomUtils
	{
		private static readonly char[] CharsToReplace = new[] { 
			' ', '\x00a0', ',', ';', '|', '~', '@', '#', '%', '^', '&', '*', '+', '-', '/', 
			'\\', '<', '>', '?', '[', ']', '(', ')', '{', '}', '"', '\'', '!'
		};
		public static string GetValidIdentifier(this CodeDomProvider provider, string identifier, bool isNamespace = false)
		{
			if (identifier == null)
				throw new ArgumentNullException("identifier");

			if (provider == null)
				throw new ArgumentNullException("provider");

			if (provider.IsValidIdentifier(identifier))
				return identifier;

			identifier = CharsToReplace.Aggregate(identifier, (current, ch) => current.Replace(ch, '_'));

			if (provider.IsValidIdentifier(identifier))
				return identifier;

			if (!isNamespace)
			{
				identifier = provider.CreateEscapedIdentifier(identifier);
				if (provider.IsValidIdentifier(identifier))
					return identifier;
			}

			identifier = "_" + identifier;
			if (provider.IsValidIdentifier(identifier))
				return identifier;

			return null;
		}

	}
}
